package com.zyk.plugin.dns;

import com.zyk.plugin.JaTransformer;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.dynamic.DynamicType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.net.InetAddress;
import java.security.ProtectionDomain;

import static net.bytebuddy.matcher.ElementMatchers.named;
import static net.bytebuddy.matcher.ElementMatchers.takesArguments;

public class InetAddressTransformer implements JaTransformer {
    public static final Logger LOG = LoggerFactory.getLogger(GetHostNameAdvice.class);

    @Override
    public String getHookClassName() {
        return "java.net.InetAddress";
    }

    @Override
    public byte[] redefineClass(ClassLoader loader, String className,
                                Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
                                byte[] classfileBuffer) {
        byte[] bytes = null;
        try {
            DynamicType.Unloaded<InetAddress> make = new ByteBuddy()
                    .redefine(InetAddress.class)
                    .visit(Advice.to(GetHostNameAdvice.class).on(named("getHostName").and(takesArguments(0))))
                    .make();
            bytes = make.getBytes();
            make.close();
        } catch (Exception e) {
            LOG.error("{} 转换失败!", getHookClassName(), e);
            return null;
        }
        return bytes;
    }
}